package com.yunpuvip.sachet.modular.util.sms;



import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsResponse;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.yunpuvip.sachet.modular.core.exception.GunsException;
import com.yunpuvip.sachet.modular.core.exception.RestServiceExceptionEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 阿里云短信
 *
 * @author zwj
 * @date 2018年1月29日  新建
 */
public class AliyunSms {

    private final static Logger logger = LoggerFactory.getLogger(AliyunSms.class);
    /**
     * 短信
     * @param phone
     * @param code
     * @return
     * @throws ClientException
     */
    public static SendSmsResponse sendSms(String phone, String code, String templateCode) throws ClientException {

        //可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout",AliyunConfig.CONNECTTIMEOUT);
        System.setProperty("sun.net.client.defaultReadTimeout", AliyunConfig.READTIMEOUT);

        //初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile(AliyunConfig.AREA, AliyunConfig.ACCESSKEYID,AliyunConfig.ACCESSKEYSECRET);
        DefaultProfile.addEndpoint(AliyunConfig.AREA, AliyunConfig.AREA, AliyunConfig.PRODUCT, AliyunConfig.DOMAIN);
        IAcsClient acsClient = new DefaultAcsClient(profile);

        //组装请求对象-具体描述见控制台-文档部分内容
        SendSmsRequest request = new SendSmsRequest();
        //必填:待发送手机号
        request.setPhoneNumbers(phone);
        //必填:短信签名-可在短信控制台中找到
        request.setSignName(AliyunConfig.SIGNNAME);
        //必填:短信模板-可在短信控制台中找到
        request.setTemplateCode(templateCode);
        //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
        request.setTemplateParam("{\"code\":\"" + code + "\"}");
        //hint 此处可能会抛出异常，注意catch
        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
        return sendSmsResponse;
    }


    /**
     * 发送催缴短信
     * @param phone
     * @param data
     * @param fishPhone
     * @param templateCode
     * @return
     * @throws ClientException
     */
    public static SendSmsResponse sendSmsOfData(String phone, String data,String fishPhone, String templateCode) throws ClientException {

        //可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout",AliyunConfig.CONNECTTIMEOUT);
        System.setProperty("sun.net.client.defaultReadTimeout", AliyunConfig.READTIMEOUT);

        //初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile(AliyunConfig.AREA, AliyunConfig.ACCESSKEYID,AliyunConfig.ACCESSKEYSECRET);
        DefaultProfile.addEndpoint(AliyunConfig.AREA, AliyunConfig.AREA, AliyunConfig.PRODUCT, AliyunConfig.DOMAIN);
        IAcsClient acsClient = new DefaultAcsClient(profile);

        //组装请求对象-具体描述见控制台-文档部分内容
        SendSmsRequest request = new SendSmsRequest();
        //必填:待发送手机号
        request.setPhoneNumbers(phone);
        //必填:短信签名-可在短信控制台中找到
        request.setSignName(AliyunConfig.SIGNNAME);
        //必填:短信模板-可在短信控制台中找到
        request.setTemplateCode(templateCode);
        //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
        //request.setTemplateParam("{\"code\":\"" + code + "\"}");
         request.setTemplateParam("{\"data\":\"" + data + "\",\"phone\":\"" + fishPhone + "\" }");
        //hint 此处可能会抛出异常，注意catch
        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
        return sendSmsResponse;
    }


    /**
     * 短信
     *
     * @param phone
     * @param code
     * @return
     * @throws ClientException
     */
    public static SendSmsResponse sendSms(String phone, String code, Integer sendType) throws ClientException {
        System.out.println("sendType:" + sendType);
        if (SMSTemplateType.REGISTER.getCode().equals(sendType)) {
            System.out.println("发送注册");
            // 注册验证码
            return sendSms(phone, code, AliyunConfig.RegisterConfig.TEMPLATECODE);
        } else {
            return sendSms(phone, code, AliyunConfig.PlatformConfig.TEMPLATECODE);
        }
    }

    /**
     * 催缴短信
     *
     * @param phone
     * @param data
     * @return
     * @throws ClientException
     */
    public static SendSmsResponse sendSmsMsg(String phone, String data,String fishPhone, Integer sendType) throws ClientException {
        System.out.println("sendType:" + sendType);
        if(SMSTemplateType.EXIPRE.getCode().equals(sendType)){
            // 发送催缴短信
            System.out.println("发送催缴短信");
            return sendSmsOfData(phone, data,fishPhone, AliyunConfig.ExpirePaymentConfig.TEMPLATECODE);
        }else {
            return null;
        }

    }







    /**
     * 查看信息
     * @param bizId
     * @param phone
     * @return
     * @throws ClientException
     */
    public static QuerySendDetailsResponse querySendDetails(String bizId, String phone) throws ClientException {

        //可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout",AliyunConfig.CONNECTTIMEOUT);
        System.setProperty("sun.net.client.defaultReadTimeout", AliyunConfig.READTIMEOUT);

        //初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile(AliyunConfig.AREA, AliyunConfig.ACCESSKEYID, AliyunConfig.ACCESSKEYSECRET);
        DefaultProfile.addEndpoint(AliyunConfig.AREA,AliyunConfig.AREA,AliyunConfig.PRODUCT,AliyunConfig.DOMAIN);
        IAcsClient acsClient = new DefaultAcsClient(profile);

        //组装请求对象
        QuerySendDetailsRequest request = new QuerySendDetailsRequest();
        //必填-号码
        request.setPhoneNumber(phone);
        //可选-流水号
        request.setBizId(bizId);
        //必填-发送日期 支持30天内记录查询，格式yyyyMMdd
        SimpleDateFormat ft = new SimpleDateFormat("yyyyMMdd");
        request.setSendDate(ft.format(new Date()));
        //必填-页大小
        request.setPageSize(10L);
        //必填-当前页码从1开始计数
        request.setCurrentPage(1L);

        //hint 此处可能会抛出异常，注意catch
        QuerySendDetailsResponse querySendDetailsResponse = acsClient.getAcsResponse(request);

        return querySendDetailsResponse;
    }

    /**
     * 短信
     * @param phone
     * @param code
     * @throws ClientException
     * @throws InterruptedException
     */
    public static void send(String phone, String code, Integer sendType) throws ClientException, InterruptedException{
        //发短信
        SendSmsResponse response = sendSms(phone, code, sendType);
        logger.info("短信接口返回的数据----------------");
        logger.info("Code=" + response.getCode());
        logger.info("Message=" + response.getMessage());
        logger.info("RequestId=" + response.getRequestId());
        logger.info("BizId=" + response.getBizId());
        //调试信息
        Thread.sleep(3000L);
        //调试信息
        if(response.getCode() != null && response.getCode().equals("OK")) {
            QuerySendDetailsResponse querySendDetailsResponse = querySendDetails(response.getBizId(),phone);
            System.out.println("短信明细查询接口返回数据----------------");
            System.out.println("Code=" + querySendDetailsResponse.getCode());
            System.out.println("Message=" + querySendDetailsResponse.getMessage());
            int i = 0;
            for(QuerySendDetailsResponse.SmsSendDetailDTO smsSendDetailDTO : querySendDetailsResponse.getSmsSendDetailDTOs())
            {
                System.out.println("SmsSendDetailDTO["+i+"]:");
                System.out.println("Content=" + smsSendDetailDTO.getContent());
                System.out.println("ErrCode=" + smsSendDetailDTO.getErrCode());
                System.out.println("OutId=" + smsSendDetailDTO.getOutId());
                System.out.println("PhoneNum=" + smsSendDetailDTO.getPhoneNum());
                System.out.println("ReceiveDate=" + smsSendDetailDTO.getReceiveDate());
                System.out.println("SendDate=" + smsSendDetailDTO.getSendDate());
                System.out.println("SendStatus=" + smsSendDetailDTO.getSendStatus());
                System.out.println("Template=" + smsSendDetailDTO.getTemplateCode());
            }
            System.out.println("TotalCount=" + querySendDetailsResponse.getTotalCount());
            System.out.println("RequestId=" + querySendDetailsResponse.getRequestId());
        }else {
            throw new GunsException(RestServiceExceptionEnum.SMS_ERROR);
        }

    }

      /**
     * 催缴短信
     * @param phone
     * @param data
     * @throws ClientException
     * @throws InterruptedException
     */
    public static void sendSmsData(String phone, String data,String fishphone, Integer sendType) throws ClientException, InterruptedException{
        //发短信
        SendSmsResponse response = sendSmsMsg(phone, data,fishphone, sendType);
        logger.info("短信接口返回的数据----------------");
        logger.info("Code=" + response.getCode());
        logger.info("Message=" + response.getMessage());
        logger.info("RequestId=" + response.getRequestId());
        logger.info("BizId=" + response.getBizId());
        //调试信息
        Thread.sleep(3000L);
        //调试信息
        if(response.getCode() != null && response.getCode().equals("OK")) {
            QuerySendDetailsResponse querySendDetailsResponse = querySendDetails(response.getBizId(),phone);
            System.out.println("短信明细查询接口返回数据----------------");
            System.out.println("Code=" + querySendDetailsResponse.getCode());
            System.out.println("Message=" + querySendDetailsResponse.getMessage());
            int i = 0;
            for(QuerySendDetailsResponse.SmsSendDetailDTO smsSendDetailDTO : querySendDetailsResponse.getSmsSendDetailDTOs())
            {
                System.out.println("SmsSendDetailDTO["+i+"]:");
                System.out.println("Content=" + smsSendDetailDTO.getContent());
                System.out.println("ErrCode=" + smsSendDetailDTO.getErrCode());
                System.out.println("OutId=" + smsSendDetailDTO.getOutId());
                System.out.println("PhoneNum=" + smsSendDetailDTO.getPhoneNum());
                System.out.println("ReceiveDate=" + smsSendDetailDTO.getReceiveDate());
                System.out.println("SendDate=" + smsSendDetailDTO.getSendDate());
                System.out.println("SendStatus=" + smsSendDetailDTO.getSendStatus());
                System.out.println("Template=" + smsSendDetailDTO.getTemplateCode());
            }
            System.out.println("TotalCount=" + querySendDetailsResponse.getTotalCount());
            System.out.println("RequestId=" + querySendDetailsResponse.getRequestId());
        }else {
            throw new GunsException(RestServiceExceptionEnum.SMS_ERROR);
        }

    }






    public static void main(String[] args) throws ClientException, InterruptedException {
        send("13538774847", "asd",1);
    }


}